# -*- encoding=utf8 -*-
__author__ = "jwjwchen"
"""自动回复,自动发货"""
import sys,os,argparse
sys.path.append(os.getcwd())
from auto_reply_fun import *
from auto_reply_config import *
from airtest.core.api import *
import random

parser = argparse.ArgumentParser(description='manual to this script')
parser.add_argument('--devices', type=str, default = None)
args = parser.parse_args()
if args.devices:
    devices_uri="android://127.0.0.1:5037/%s?cap_method=javacap&touch_method=adb"%(args.devices)
else:
    devices_uri="android:///"
connect_device(devices_uri)

from poco.drivers.android.uiautomation import AndroidUiautomationPoco
poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
x,y = poco.get_screen_size()
#---------------调试
#---------------调试

#--------------初始化咸鱼app-----------------------    
package = "com.taobao.idlefish"
init_idle_fish(package)
#--------------提示升级，点击不升级-----------------------
sleep(18)
if poco(text='暂不升级').exists():
    poco(text='暂不升级').click()
#-------------------------------------------------
message_tap = poco(nameMatches='^消息.*状态$',selected=False)  #消息标签
wait_for_appearance_and_click(message_tap) #点击消息标签
refresh_time = 0 #初始化翻页次数,每翻页一次该值自增1
select_photo_time = 0 #初始化相片选择次数,每选择一次,该值自增1
i = 1  #初始化售卖轮数,每轮完成后,该值自增1
while True:
    try:
        #----------------------------------------------------------------
        if poco(textMatches='^休息会呗，坐下来喝口水.*$').exists():
            swipe((0.2*x,0.58*y),(0.8*x,0.58*y),duration=1)
            sleep(5)
        sleep(3)
        have_msg_mark = poco(type="android.widget.TextView",name='com.taobao.idlefish:id/msg_tag_debug_text_id',textMatches="\d")
        #print ("当前有 %d 个消息"%(len(have_msg_mark)))
        if have_msg_mark.exists():  #判断消息是否存在
            have_msg_mark.click() #点击第一条消息
            sleep(2)
            swipe((0.5*x,0.8*y),(0.5*x,0.2*y),duration=0.5)
            
            if poco(textMatches='^休息会呗，坐下来喝口水.*$').exists():
                swipe((0.2*x,0.58*y),(0.8*x,0.58*y),duration=1)
                sleep(5)
            #----点开消息页面获取元素-----------------------------------------
            msg_title = poco(text="消息",name="com.taobao.idlefish:id/center_text") #获取 消息标题 元素
            go_to_delivery = poco(text="去发货",name="android.view.View") #获取 去发货元素
            wait_the_seller_deliver = poco(text="等待卖家发货",name="android.view.View") #获取 等待卖家发货元素
            wait_the_buyer_payment = poco(text="等待买家付款",name="android.view.View") #获取 等待卖家发货元素
            wait_the_Meet_trading = poco(text="等待见面交易",name="android.view.View") #获取 等待见面交易元素
            trade_successfully = poco(text="交易成功",name="android.view.View") #获取 交易成功元素
            refund_successfully = poco(text="退款成功",name="android.view.View") #获取 退款成功元素
            before_trade = poco(text="交易前聊一聊",name="android.view.View") #获取 交易前聊一聊元素
            dialogue_msg_list = poco(name='android.view.View',longClickable=True) #获取 消息列表
            dialogue_msg_list_ = poco(name='com.taobao.idlefish:id/cell_text',longClickable=True) #获取 消息列表_
            Buyers_evaluation_in_msg_list = poco(textMatches="^(.*[\s\S]买家已评价|买家已评价)[\s\S]*",touchable=True) #获取 消息队列中 买家已评价元素
            trade_successfully_in_msg_list = poco(textMatches="^(.*[\s\S]交易成功！|交易成功！)[\s\S]*",touchable=True) #获取 消息队列中 交易成功 元素
            replay_box = poco(text="想跟TA说点什么呢",touchable=True)
            send_msg = poco(text="发送",touchable=True)
            has_been_payment = poco(textMatches="^已付款，等待您发货[\s\S]*",touchable=True)
            please_deliver = poco(textMatches="^请尽快预约快递发货[\s\S]*",touchable=True)
            plus_sign_pos = (0.95*x,0.94*y) #加号坐标
            cancel_advertising = (0.48*x,0.66*y) #取消广告坐标
            photo = poco(textMatches="^相册.*$",touchable=True)
            photo_list = poco(name="图片未选中")
            done = poco(textMatches="^完成.*$",touchable=True)
            do_not_to_send = poco(text="无需寄件",touchable=True)
            continue_to_send = poco(text="继续",touchable=True)
            has_been_delivery = poco(textMatches="^已发货[\s\S]*",touchable=True)
            #----买家拍下并付款场景,执行发货步骤-----------------------------------------
            if go_to_delivery.exists() and wait_the_seller_deliver.exists():
                touch(plus_sign_pos) #点击+号按钮
                wait_for_appearance_and_click(photo) #点击相册图标
                photo_list = poco(name="图片未选中")  #列出相册列表
                photo_list_count = len(photo_list) #获取图片总数
                #-------------相册选择自增器------------------
                if round_sales: #轮流售卖
                    if i>=photo_list_count: #不会选到第一张,因为第一张是赠送账号
                        i=1
                    _index = photo_list_count - i
                    i+=1
                else: #固定售卖
                    if select_photo_time >= number_of_sales: #会选到第一张,最后卖完了只能卖第一张了
                        select_photo_time = 0 #一轮下来后，统计次数归零
                        i+=1                  #一轮下来后，图片下标加1
                    _index = photo_list_count - i  #图片下标索引
                #-------------自增器分割线------------------
                wait_for_appearance_and_click(photo_list[_index])  #点击最后一张照片
                wait_for_appearance_and_click(done)  #点击完成图片的发送
                go_to_delivery.click() #去发货
                sleep(3) #等待跳出广告
#                 touch(cancel_advertising) #取消广告
                wait_for_appearance_and_click(do_not_to_send)  #无需发货
                wait_for_appearance_and_click(continue_to_send)  #继续发货
                replay_box.click()  #点击回复框
                text(urge_confirm_receipt,enter=False) #催他收货
                sleep(2)
                wait_for_appearance_and_click(send_msg) #发送消息
                keyevent("BACK")
                sleep(2)   #其他手机需要返回两次
                keyevent("BACK")  #其他手机需要返回两次
                select_photo_time+=1 #统计发送次数,加1
            #----------------------------------------------------
            
            
            #----买家拍下但并未付款的场景,直接返回-----------------------------------------
            elif wait_the_buyer_payment.exists():
                keyevent("BACK")  #其他手机需要返回两次
            
            
            #----交易成功并且给好评的场景,赠送他两天的网盘-----------------------------------------
            elif trade_successfully_in_msg_list.exists() and Buyers_evaluation_in_msg_list.exists():
                touch(plus_sign_pos) #点击+号按钮
                wait_for_appearance_and_click(photo) #点击相册图标
                photo_list = poco(name="图片未选中")  #列出相册列表
                wait_for_appearance_and_click(photo_list[0])  #点击第一张照片,第一张照片一定要放置为赠送的照片
                wait_for_appearance_and_click(done)  #点击完成图片的发送
                sleep(2)
                replay_box.click()  #点击回复框
                text(express_gratitude,enter=False) #表达感谢
                sleep(2)
                wait_for_appearance_and_click(send_msg) #发送消息
                keyevent("BACK")
                sleep(2)   #其他手机需要返回两次
                keyevent("BACK")  #其他手机需要返回两次
            
            
            #----检测到退款成功时，直接返回-----------------------------------------
            elif refund_successfully.exists():
                keyevent("BACK")

            #----点击消息后,若没有进入消息页面,则中断-----------------------------------------
            elif msg_title.exists():
                swipe((0.4*x,0.2*y),(0.4*x,0.8*y),duration=0.5)
                continue    
            
            #----自动回复场景-----------------------------------------
            else:
                if dialogue_msg_list.exists():
                    dialogue_msg_count = len(dialogue_msg_list) #获取消息总数量
                    last_msg_index = dialogue_msg_count - 1 #获取最后一条消息的下标
                    last_msg = dialogue_msg_list[last_msg_index].get_text() #获取最后一条消息的内容
#                     print ("最后一条消息的内容 %s"%last_msg)
                    if last_msg : #消息不为空
                        if our_tag in last_msg: #先判断我方消息标记是否存在,若存在,则表示该消息来自我方,立即返回
#                             print ("我方消息,返回")
                            keyevent("BACK")
                        else:
                            if auto_match_reply_comment(last_msg,dialogue_msg_1):
                                dialogue_reply = dialogue_msg_1_reply
                            elif auto_match_reply_comment(last_msg,dialogue_msg_2):
                                dialogue_reply = dialogue_msg_2_reply
                            elif auto_match_reply_comment(last_msg,dialogue_msg_3):
                                dialogue_reply = dialogue_msg_3_reply
                            elif auto_match_reply_comment(last_msg,dialogue_msg_4):
                                dialogue_reply = dialogue_msg_4_reply
                            elif auto_match_reply_comment(last_msg,dialogue_msg_5):
                                dialogue_reply = dialogue_msg_5_reply
                            elif auto_match_reply_comment(last_msg,dialogue_msg_6):
                                dialogue_reply = dialogue_msg_6_reply
                            elif auto_match_reply_comment(last_msg,dialogue_msg_7):
                                dialogue_reply = dialogue_msg_7_reply
                            elif auto_match_reply_comment(last_msg,dialogue_msg_8):
                                dialogue_reply = dialogue_msg_8_reply
                            else:
                                dialogue_reply = default_reply
                            replay_box.click()
                            text(dialogue_reply,enter=False)
                            sleep(1)
                            wait_for_appearance_and_click(send_msg)
                            keyevent("BACK")
                            sleep(1)   #其他手机需要返回两次
                            keyevent("BACK")  #其他手机需要返回两次
                    else:#消息为空
                        dialogue_reply = dialogue_msg_None_reply
                        replay_box.click()
                        text(dialogue_reply,enter=False)
                        sleep(1)
                        wait_for_appearance_and_click(send_msg)
                        keyevent("BACK")
                        sleep(1)   #其他手机需要返回两次
                        keyevent("BACK")  #其他手机需要返回两次
                else:
                    keyevent("BACK")

        else:
            if refresh_time>=page_times: #向上翻页
                for _ in range(page_times+4):
                    swipe((0.4*x,0.2*y),(0.4*x,0.8*y),duration=0.5)
                    if poco(text='通知消息',name="com.taobao.idlefish:id/item_title").exists():
                        refresh_time = 0  #翻页计数器归零
                        break
                if not poco(text='通知消息',name="com.taobao.idlefish:id/item_title").exists():
                    raise Exception("未知错误")
            else:
                swipe((0.5*x,0.8*y),(0.5*x,0.2*y),duration=0.5)
                refresh_time+=1 #翻页计数器增加一次
            
    except Exception as e:
#         print ("出现异常:",e)
        init_idle_fish(package)
        #--------------提示升级，点击不升级-----------------------
        sleep(18)
        if poco(text='暂不升级').exists():
            poco(text='暂不升级').click()
        #-------------------------------------------------
        wait_for_appearance_and_click(poco(nameMatches='^消息.*状态$',selected=False)) #点击消息标签

        
    
    
    
 
